<?php

// RED BEANS help: http://redbeanphp.com/


require './libraries/rb.phar';

R::setup('mysql:host=ltpo2.fri1.uni-lj.si;dbname=s6_2014',
        's6gu',
        'xcts9hq6');

//other helpers
include "./helperScripts/help.php";

/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CHANGE THIS FILE FROM TPO TO SMPRO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*

define("DB_SERVER_NAME", "ltpo2.fri1.uni-lj.si");
define("DB_NAME",        "s6_2014");
define("USERNAME",       "s6gu");
define("PASSWORD",       "xcts9hq6");

function getDatabase() {
    
	if( !($database = mysql_connect( DB_SERVER_NAME, USERNAME, PASSWORD )))
		die(" <p> Could not connect to database " .  mysql_error() . "</p>");
		
	if ( !mysql_select_db(DB_NAME, $database))
		die(" <p> Could not open ". DB_NAME ." database </p>");
	
	return $database;	
}
//Funkcija za izpis vseh dropdown uporabnikov, samo opcije dropdown lista. Sprejme id uporabnika, ki je primarno označen
function dropDownUsers($selected){
    $query = "SELECT id, username FROM user";
    $result = executeQuery($query);
    
    while($row = mysql_fetch_array($result)){
        //Če imamo uporabnika, ki mora biti primarno izbran na HTML strani
        ($selected == $row['id']) ? $selec="selected" : $selec="";
        echo "<option value='".$row['id']."' $selec>".$row['username']."</option>";
    }
}

//Funkcija za izvedbo SQL poizvedbe
function executeQuery($query){
    $db = getDatabase();
    //Za šumnike
    mysql_query('SET character_set_results="utf8"');
    if ( !( $result = mysql_query( $query, $db ) ) ) {
            print( "<p>Could not execute query -> $query!</p>" );   //Samo za debugiranje, treba izbrisat izpis queryja!!
            die( mysql_error() . "</body></html>" );
     }

     mysql_close( $db );
     return $result;
}
function executeQueryRowsAffected($query){
    $db = getDatabase();
    //Za šumnike
    mysql_query('SET character_set_results="utf8"');
    if ( !( $result = mysql_query( $query, $db ) ) ) {
            print( "<p>Could not execute query -> $query!</p>" );   //Samo za debugiranje, treba izbrisat izpis queryja!!
            die( mysql_error() . "</body></html>" );
     }
     $rows_affected = mysql_affected_rows();
     mysql_close( $db );
     return $rows_affected;
}
function checkAdmin($id){
    $query = "SELECT admin FROM user WHERE id='$id'";
    $res = executeQuery($query);
    $row = mysql_fetch_array($res);
    return $row['admin'];
}

//Funkcija, ki prebere sporocilo, katerega ID je poslan z GET zahtevkom, shranjeno v bazi
function showMessage(){
    if(isset($_GET['msg'])){
        $id=$_GET['msg'];
    
        $query="SELECT content FROM message WHERE id_msg='$id'";
        $result = executeQuery($query);
        //Samo, če obstaja zapis
        if(mysql_num_rows($result)>0){
            $row = mysql_fetch_array($result);
		    echo $row['content'];	
//            if($id < 200){
//                echo "<p class='err_msg'>".$row['content']."</p>";
//            }
//            else{
//                echo "<p class='suc_msg'>".$row['content']."</p>";
//            }
        }
        //Samo za debuganje
        else{
            echo "<p class='err_msg'><<<<< Ne najdem tega zapisa v bazi, verjetno napacen ID sporocila >>>>>>></p>";
        }
    }
}
function message($id){

	$query="SELECT content FROM message WHERE id_msg='$id'";
    $result = executeQuery($query);
    //Samo, če obstaja zapis
        if(mysql_num_rows($result)>0){
            $row = mysql_fetch_array($result);
		    return $row['content'];	
        }
}
function getCurrentSprint($curr_proj){
	$querySprint = "SELECT * FROM sprint WHERE project_id='$curr_proj';";
	$querySprintResult = executeQuery($querySprint);
		while ($row = mysql_fetch_array($querySprintResult)) {
			$sprint_id = 		$row['sprint_id'];
			$start_date = 		$row['start_date'];
			$finish_date = 		$row['finish_date'];
			$velocity = 		$row['velocity'];
			$sprint_number = 	$row['sprint_number'];
						
			$today = date("Y-m-d");
			$today = strtotime($today);	
						
			$start_date_compare = strtotime($start_date);
			$finish_date_compare = strtotime($finish_date);
			
			if ($today >= $start_date_compare && $today <= $finish_date_compare){
				return $sprint_id;
			}
		}
}
function getUsername($id){
    $query = "SELECT username FROM user WHERE id = '$id'";
    return mysql_fetch_array(executeQuery($query))[0];
}
function isScrumMaster($user_id, $project_id){
    $query = "SELECT * FROM project WHERE project_id = '$project_id' AND scrum_master='$user_id'";
    if(executeQueryRowsAffected($query) == 1)
        return true;
    else return false;
}

function burnDown($hours_spentORwork){
    //$hours_spentORwork can be equal to 'hours_spent' or 'hours_work' MYSQL field in task_work table
    //PARSING DATA
    //GET project id
    if(session_id() == '') {
        session_start(); // session isn't started
    }
    $user_id=$_SESSION['id'];
    $query = "SELECT current_project FROM user WHERE id='$user_id'";
    $project_id = mysql_fetch_array(executeQuery($query))[0];

    //GETTING START AND END DAY 
    $queryTW = "SELECT * FROM task t, task_work tw, story s WHERE t.task_id=tw.task_id AND s.story_id=t.story_id AND project_id = '34'";
    $queryTW_start_date = $queryTW." ORDER BY tw.date ASC LIMIT 1";
    $start_date = mysql_fetch_array(executeQuery($queryTW_start_date))['date'];
    //First sprint day may be sooner than first work day
    $query = "SELECT start_date FROM sprint WHERE project_id = '$project_id' ORDER BY start_date ASC LIMIT 1";
    $first_date = mysql_fetch_array(executeQuery($query))[0];
    
    $queryTW_end_date = $queryTW." ORDER BY tw.date DESC LIMIT 1";
    $row = mysql_fetch_array(executeQuery($queryTW_end_date));
    $last_date = $row['date'];
    $today = date("Y-m-d");
    //GETTING ALL DATES between them
    $dates =  getDays($first_date,$today);    
    
    //READING all table with work remaining and date
    $query = "SELECT date, $hours_spentORwork FROM task_work tw, task t, story s WHERE t.task_id =  tw.task_id AND s.story_id = t.story_id AND s.project_id = '$project_id'";
    $result = executeQuery($query);
    $taskDateWork =array(); 
    while($taskDateWork[] = mysql_fetch_array($result)){}
    //$query = "SELECT COUNT(hours_remaining) FROM task_work tw, task t, story s WHERE t.task_id =  tw.task_id AND s.story_id = t.story_id AND s.project_id = '$project_id' AND tw.date='$val'";
    
    //SUM all work to do according to date
    foreach ($taskDateWork as $key => $val){
        //$work_today = mysql_fetch_array(executeQuery($query))[0];
        //Empty space in query...
        if(isset($val['date']))
            $dates[$val['date']] += $val["$hours_spentORwork"];
    }
    foreach ($dates as $key=>$val){
        if($start_date == $key)
            break;
        $dates[$key]=$dates[$start_date];
        
    }
    //If we are calculating workload we must sum all done work by that day
    if($hours_spentORwork=="hours_spent"){
        $dates = array_values($dates);
        for($i=0; $i<count($dates)-1;$i++){
            $dates[$i+1]+=$dates[$i];
        }
    }
    $query = "SELECT * FROM task_work tw, task t, story s WHERE t.task_id = tw.task_id AND s.story_id = t.story_id AND s.project_id = '$project_id' AND tw.date = $today";
    $last_day_work = (executeQueryRowsAffected($query)>0)?true:false;
    return fillZeroValues($dates, $last_day_work);
}
//We have some zero values in array, which is not correct, except that at the beginning
function fillZeroValues($dates, $last_day_work){
    
    
    $values = array_values($dates);
    $keys = array_keys($dates);
    for($i = 1; $i<count($dates); $i++){
        if($values[$i]==0 && ($i!=(count($values)-1) || !$last_day_work)){
            //for right algorithm we have to change also values
            $values[$i]=$values[$i-1];
            $dates[$keys[$i]]=$values[$i-1];
        }
    }
    return $dates;
}
//Function gets all sprints from currently selected project of current user
function getSprints(){
    if(session_id() == '') {
        session_start(); // session isn't started
    }
    //Get current project id
    $user_id=$_SESSION['id'];
    $query = "SELECT current_project FROM user WHERE id='$user_id'";
    $project_id = mysql_fetch_array(executeQuery($query))[0];
    
    $query = "SELECT start_date FROM sprint WHERE project_id = '$project_id'";
    $result = executeQuery($query);
    $sprints = array();

    //Get all start sprint dates
    while($sprints[] = mysql_fetch_array($result)[0]){}
    //Return them
    return $sprints;
}
function getDays($startTime, $endTime){  
    $day = 86400;   //Čas enega dneva v sekundah 
    $format = 'Y-m-d';
    $startTime = strtotime($startTime);
    $endTime = strtotime($endTime);
    $numDays = round(($endTime - $startTime) / $day) + 1;
    $days = array();
        
    for ($i = 0; $i < $numDays; $i++) {
        $days[date($format, ($startTime + ($i * $day)))] = 0;
    }
        
    return $days;

}  
function getSprintsStartDates(){
    $user_id=$_SESSION['id'];
    $query = "SELECT current_project FROM user WHERE id='$user_id'";
    $project_id = mysql_fetch_array(executeQuery($query))[0];
    
    $query = "SELECT start_date FROM sprint WHERE project_id = '$project_id'";
    $result = executeQuery($query);
    $starts = array();
    while($starts[] = mysql_fetch_array($result) ){};
    return $starts;
}
//Funkcija, ki prebere sporocilo poslano iz druge skripte, napake imajo prednost
/*function showMessage(){
    $result = -1;    //Vrnemo rezultat, -1-ni sporocila, 0-brez napak, success; 1-napaka, error
    if(isset($_SESSION['error'])){
        $msg = $_SESSION['error'];
        $result = 1;
    }
    else if(isset($_SESSION['success'])){
        $msg = $_SESSION['success'];
        $result = 0;
    }
    else echo $_SESSION['error'];
    if(isset($msg)){
        echo  "<h2 style='color: red'>$msg</h2>";
    }
    //Ponastavimo spremenljivki
    unset($_SESSION['success']);
    unset($_SESSION['error']);
    
    return $result;
}
*/

?>
